package dt.inlee.common.util;

import java.sql.Connection;
import java.sql.SQLException;

import dt.inlee.common.exception.FrameworkException;

/**
 * 事务管理器
 * 
 */
public class MyTransactionManager {
	private Connection conn;

	public MyTransactionManager(Connection conn) {
		this.conn = conn;
	}

	/** 开启事务 */
	public void beginTransaction() throws FrameworkException {
		try {
			conn.setAutoCommit(false); // 把事务提交方式改为手工提交
		} catch (SQLException e) {
			throw new FrameworkException("开户事务时出现异常:" + e.getMessage());
		}
	}

	/** 提交事务并关闭连接 */
	public void commitAndClose() throws FrameworkException {
		try {
			conn.commit(); // 提交事务
		} catch (SQLException e) {
			throw new FrameworkException("提交事务时出现异常：" + e.getMessage());
		} finally {
			if (BaseUtil.isEmpty(conn)) {
				try {
					conn.close();
				} catch (SQLException e) {
					throw new FrameworkException("关闭连接时：" + e.getMessage());
				}
			}
		}
	}

	/** 回滚并关闭连接 */
	public void rollbackAndClose() throws FrameworkException {
		try {
			conn.rollback();
		} catch (SQLException e) {
			throw new FrameworkException("回滚事务时出现异常:" + e.getMessage());
		} finally {
			if (BaseUtil.isEmpty(conn)) {
				try {
					conn.close();
				} catch (SQLException e) {
					throw new FrameworkException("关闭连接时：" + e.getMessage());
				}
			}
		}
	}
}